import request from '@/utils/request'
import { getToken } from '@/utils/auth' 

// 查询销项发票列表
export function listInvoice(query) {
  return request({
    url: '/invoice/invoice/list',
    method: 'get',
    params: query
  })
}

// 查询销项发票详细
export function getInvoice(id) {
  return request({
    url: '/invoice/invoice/' + id,
    method: 'get'
  })
}

// 新增销项发票
export function addInvoice(data) {
  return request({
    url: '/invoice/invoice',
    method: 'post',
    data: data
  })
}

// 修改销项发票
export function updateInvoice(data) {
  return request({
    url: '/invoice/invoice',
    method: 'put',
    data: data
  })
}

// 删除销项发票
export function delInvoice(id) {
  return request({
    url: '/invoice/invoice/' + id,
    method: 'delete'
  })
}



// 导出销项发票
export function exportInvoice(query) {
  // 构建导出参数
  const exportParams = {
    pageNum: 1,
    pageSize: 999999,  // 设置较大的数值以获取所有数据
    invoiceNumber: query.invoiceNumber,
    invoiceType: query.invoiceType,
    customerName: query.customerName,
    voidOrNot: query.voidOrNot,
    beginInvoiceDate: query.beginInvoiceDate,
    endInvoiceDate: query.endInvoiceDate
  };

  // 过滤掉值为undefined或null的参数
  Object.keys(exportParams).forEach(key => {
    if (exportParams[key] === undefined || exportParams[key] === null) {
      delete exportParams[key];
    }
  });

  return request({
    url: '/invoice/invoice/export',
    method: 'post',
    data: exportParams,
    responseType: 'blob',
    headers: {
      'Content-Type': 'application/json'
    },
    timeout: 60000
  }).then(response => {
    // 检查响应是否为空
    if (!response || response.size === 0) {
      throw new Error('导出数据为空');
    }

    // 正常的 Excel 文件下载
    const timestamp = new Date().getTime();
    const filename = `销项发票数据_${timestamp}.xlsx`;
    const blob = new Blob([response.data || response], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });

    // 检查 blob 是否为空
    if (blob.size === 0) {
      throw new Error('导出数据为空');
    }

    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(link.href);
  }).catch(error => {
    console.error('导出错误:', error);
    throw error;
  });
}



